<template>
  <div>
    <div id="player">
    </div>

    <el-button @click="kaibo">开播</el-button>
    <a :href=this.live.liveUrl target=”_self”>点我去直播</a>
  </div>

</template>

<script>
import { createWatchCore } from '@polyv/live-watch-sdk';
import { PolyvWatchCoreEvents } from '@polyv/live-watch-sdk';
import axios from "axios";

export default {
  components: {

  },
  data() {
    return {
      playerJs: 'https://player.polyv.net/resp/live-h5-player/latest/liveplayer.min.js',
      live:{},
    };
  },
  async created() {
    this.watchCore = createWatchCore({
      channelId: 'xxx', // 传入观看页的频道号
    });
    // 监听 setup 钩子
    this.watchCore.eventEmitter.on(PolyvWatchCoreEvents.WatchCoreSetuped, () => {
      console.info('观看页核心实例安装完成');
    });
    // 观众未进行观看条件授权
    if (!watchCore.auth.isAuthorized()) {
      // TODO：显示引导/授权页

      // 观众点击观看页入口或执行观看条件授权，如：无条件授权
      const result = await watchCore.auth.verifyNoneAuth();
      if (!result.success) {
        console.error('授权失败了！！', result.failReason);
        return;
      }

      // 当观众执行观看条件授权成功，需要重新安装 watchCore
      await watchCore.setup();
    }

// 如果需要互动功能，建议可以先安装互动 SDK，才能保证互动功能够及时显示
// watchCore.interactReceive.setupIarCore()

// 当完成观看条件授权后，即可连接聊天室进入直播观看页
    await watchCore.connect();

// TODO：连接成功，显示直播观看页
    // 安装核心实例
    await this.watchCore.setup();
  },
  mounted() {
    this.loadPlayerScript(this.loadPlayer);
  },
  methods: {
    kaibo(){
      axios.post("http://localhost:9000/live/kaibo/").then(res=>{
        if (res.data.code === 200){
          alert("直播已开启")
        }
        this.live=res.data.data;
        console.log(this.live.channelId);
        console.log(this.live.channelPasswd);
        console.log(this.live.userId);
        this.loadPlayer();

      })
    },
    loadPlayerScript(callback) {
      if (!window.polyvLivePlayer) {
        const myScript = document.createElement('script');
        myScript.setAttribute('src', this.playerJs);
        myScript.onload = callback;
        document.body.appendChild(myScript);
      } else {
        callback();
      }
    },

    loadPlayer() {
      const polyvLivePlayer = window.polyvLivePlayer;
      this.player = polyvLivePlayer({
        wrap: '#player',
        width: 800,
        height: 533,
        uid: this.live.userId ,
        vid: this.live.channelId,
      });
    }
  },
  destroyed() {
    if (this.player) {
      this.player.destroy();
    }
  }
}
</script>

<style>

</style>
